<template>
  <div class="JNPF-common-layout">
    <div class="JNPF-common-layout-center">
      <el-row class="JNPF-common-search-box" :gutter="16">
        <el-form @submit.native.prevent label-width="80px" label-position="left">
          <el-col :span="6">
            <el-form-item label="客户名称">
        <el-select v-model="listQuery.fsiteNo" disabled clearable filterable class="filter-item" placeholder="请选择所属场地">
          <el-option v-for="item in fsiteNoBelongOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="场景名称">
        <el-input v-model="listQuery.fscenename" clearable class="filter-item" style="width: 200px;"
          placeholder="请输入场景名称" />
      </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="存储分类">
        <el-select v-model="listQuery.fstorageflag" clearable filterable class="filter-item" placeholder="请选择存储分类">
          <el-option v-for="item in fstorageflagOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button 
              type="primary"
                @click="handleFilter">查找</el-button>
              <el-button 
              type="success"
                @click="handleCreate">添加</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="JNPF-common-layout-main JNPF-flex-main">
       <!-- 查询结果 -->
    <JNPF-table v-loading="listLoading" :data="list">
      <el-table-column align="center" label="操作" class-name="small-padding" :width="buttonColor.operationTwo">
        <template slot-scope="scope">
          <el-button type="text" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
      <el-table-column :index="indexMethod" align="center" label="序号" type="index" :width="buttonColor.line" />
      <el-table-column :width="buttonColor.name" align="left" label="场景名称" prop="fscenename" />
      <el-table-column :formatter="formatSite" align="left" label="客户名称" prop="fsiteNo" />
      <el-table-column :formatter="formatFstorageflag" align="left" label="存储分类" prop="fstorageflag" />
      <el-table-column :formatter="datetimeFormat" align="left" label="修改时间" prop="fupddate" />
    </JNPF-table>
    <paginations
      :total="total"
      :page.sync="listQuery.currentPage"
      :limit.sync="listQuery.pageSize"
      />
      </div>
    </div>
    <el-dialog  
    :fullscreen="true"
    :close-on-click-modal="false"
     :before-close="handleClose" 
     :visible.sync="dialogFormVisible">
     <el-tabs type="border-card">
      <el-tab-pane label="头表" :style="{height:screenHeight-230+'px'}">
        <el-row class="JNPF-common-search-box" :gutter="16">
        <el-form @submit.native.prevent label-width="80px" label-position="left" ref="dataForm" :rules="rules" :model="dataForm">
          <el-col :span="8">
            <el-form-item label="客户名称" prop="fsiteNo">
              <el-select v-model="dataForm.fsiteNo" disabled clearable filterable placeholder="请选择">
                <el-option v-for="item in fsiteNoBelongOptions" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="存储分类" prop="fstorageflag">
              <el-select v-model="dataForm.fstorageflag" class="filter-item" placeholder="请选择存储分类">
                <el-option v-for="item in fstorageflagOptions" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="场景名称" prop="fscenename">
              <el-input v-model="dataForm.fscenename" />
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      </el-tab-pane>
      <el-tab-pane label="明细表">
        <JNPF-table :height="screenHeight-230" v-loading="listLoading" :data="dataForm.details" stripe>
                <el-table-column :width="buttonColor.line" align="center" label="行号" prop="fno" />
                <el-table-column align="left" label="空气项目" prop="fairitem">
                  <template slot-scope="scope">
                     <el-select v-model="scope.row.fairitem" clearable filterable placeholder="请选择">
                      <el-option v-for="item in sTsAiritemOptions" :key="item.value" :label="item.label"
                        :value="item.value" />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column align="left" label="超标条件" prop="fwhere">
                  <template slot-scope="scope">
                     <el-select v-model="scope.row.fwhere" clearable filterable placeholder="请选择">
                      <el-option v-for="item in symbolOptions" :key="item.value" :label="item.label"
                        :value="item.value" />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column align="left" label="超标值" prop="fvalue">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.fvalue"  v-direction="{ x: 0, y: scope.$index,type:3}"/>
                  </template>
                </el-table-column>
                <el-table-column align="left" label="达标条件" prop="fwhere2">
                  <template slot-scope="scope">
                     <el-select v-model="scope.row.fwhere2" clearable filterable placeholder="请选择">
                      <el-option v-for="item in symbolOptions" :key="item.value" :label="item.label"
                        :value="item.value" />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column align="left" label="达标值" prop="fvalue2">
                   <template slot-scope="scope">
                    <el-input v-model="scope.row.fvalue2"  v-direction="{ x: 1, y: scope.$index,type:3}"/>
                  </template>
                </el-table-column>
                <el-table-column :width="buttonColor.operationTwo" align="center" label="操作" class-name="small-padding">
                  <template slot-scope="scope">
                    <el-button type="text" @click="handleDelete1(scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </JNPF-table>
      </el-tab-pane>
    </el-tabs>
    <span slot="footer" class="dialog-footer">
        <el-button type="info" @click="cancel()">取消</el-button>
        <el-button  v-if="dialogStatus == 'create'"
        type="primary"
          @click="createData">确定</el-button>
        <el-button type="primary" v-else @click="updateData">确定
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  listsceneHead,
  createsceneHead,
  updatesceneHead,
  deletesceneHead,
} from "@/api/sceneHead";
import { fsiteOptionsByLevel, getListArea } from "@/api/area";
import { sTsAiritemOptions } from "@/api/airAlarm";
import Pagination from "@/components/Pagination";
import { tableColor, titleColor, buttonColor } from "@/filters/index";
import moment from "moment";



export default {
  name: "ITsSceneHead",
  components: { Pagination },
  data() {
    return {
      listTmp: [],
      selectList: [],
      flineList: [],
       screenHeight: document.body.clientHeight,
      isAdd1: true,
      titleColor,
      panelHeight: 0,
      buttonColor,
      list: null,
      dataForm1: {
        fno: undefined,
        fairitem: undefined,
        fwhere: undefined,
        fvalue: undefined,
        fwhere2: undefined,
        fvalue2: undefined,
      },
      detailsTmp: null,
      dialogFormVisible1: false,
      total: 0,
      tableColor: tableColor,
      fsiteNoBelongOptions: null,
      fstorageflagOptions: null,
      sTcSceneItemListTmp: [],
      sTsAiritemOptions: [],
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        fscenename: undefined,
        fsiteNo: this.$store.state.user.fsiteNo,
        fstorageflag: undefined,
        fexectime: undefined,
        fexecweek1: undefined,
        fexecweek2: undefined,
        fexecweek3: undefined,
        fexecweek4: undefined,
        fexecweek5: undefined,
        fexecweek6: undefined,
        fexecweek7: undefined,
        fscenetype: undefined,
        foperator: undefined,
        fupddate: undefined,
        sort: "fupddate",
        order: "desc",
      },
      symbolOptions:[
        {label:">=",value:">="},
        {label:"<=",value:"<="},
        {label:">",value:">"},
        {label:"<",value:"<"},
        {label:"=",value:"="},
      ],
      dataForm: {
        fsceneno: undefined,
        fscenename: undefined,
        fsiteNo: undefined,
        fstorageflag: undefined,
        fexectime: undefined,
        fexecweek1: undefined,
        fexecweek2: undefined,
        fexecweek3: undefined,
        fexecweek4: undefined,
        fexecweek5: undefined,
        fexecweek6: undefined,
        fexecweek7: undefined,
        fscenetype: undefined,
        foperator: undefined,
        fupddate: undefined,
        id: undefined,
        details: undefined,
        sTcSceneItemList: [], // abc
      },
      sTcSceneItem: {
        fairitem: undefined,
        fwhere: undefined,
        fvalue: undefined,
        fwhere2: undefined,
        fvalue2: undefined,
      },
      details: {
        fairitem: undefined,
        fwhere: undefined,
        fvalue: undefined,
        fwhere2: undefined,
        fvalue2: undefined,
      },
      dialogFormVisible: false,
      dialogStatus: "",
      dialogStatus1: "",
      textMap: {
        update: "编辑",
        create: "创建",
      },
      dialogStatusSon: "",
      rules: {
        fscenename: [{ required: true, message: "场景名称不能为空" }],
        fsiteNo: [{ required: true, message: "所属学校不能为空" }],
        fstorageflag: [{ required: true, message: "存储分类不能为空" }],
        fscenetype: [
          { required: true, message: "场景类型不能为空" },
          { type: "number", message: "场景类型必须为数字值" },
        ],
        foperator: [{ required: true, message: "操作员不能为空" }],
        fupddate: [{ required: true, message: "修改时间不能为空" }],
      },
    };
  },
  created() {
    this.keyCode();
    this.getList();
    this.panelHeight = document.documentElement.clientHeight - 243;
    fsiteOptionsByLevel(3)
      .then((response) => {
        this.fsiteNoBelongOptions = response.data.data.list;
      })
      .catch(() => {
        this.fsiteNoBelongOptions = [];
      });
    // 存储分类
    getListArea({ flag: 28 })
      .then((response) => {
        this.fstorageflagOptions = response.data.data.list;
      })
      .catch(() => {
        this.fstorageflagOptions = [];
      });
    sTsAiritemOptions()
      .then((response) => {
        this.sTsAiritemOptions = response.data.data.list;
        // response.data.data.list.forEach((v) => {
        //   if (v.value.toString().substring(0, 1) === "2") {
        //     // 室内
        //     this.sTsAiritemOptions.push(v);
        //   }
        // });
      })
      .catch(() => {
        this.sTsAiritemOptions = [];
      });
  },
  methods: {
    //回车
    keyCode() {
      let direction = this.$getDirection();
      let _this=this;
      direction.on("keyup", function (e, val) {
        if (e.keyCode === 13) {
          if(val.y==_this.dataForm.details.length-1)
          {
            _this.addrow(res=>{
               direction.next();
            })
          }
          else
          {
           direction.next();
          }
        }
        if (e.keyCode === 37) {
          direction.previous();
        }
        if (e.keyCode === 38) {
          direction.previousLine();
        }
        if (e.keyCode === 40) {
          direction.nextLine();
        }
        if (e.keyCode == 39) {
          direction.next();
        }
      });
    },
    //添加行
    addrow(callback){
      this.dataForm.details.push({
        fno:this.dataForm.details.length+1,
        fairitem:"",
        fwhere:"",
        fvalue:"",
        fwhere2:"",
        fvalue2:""
      })
      setTimeout(()=>{
      callback(200)
      },300)
    },
    datetimeFormat(row, column) {
      const date = row[column.property];
      if (date === undefined || date === null) {
        return "";
      }
      return moment(date).format("YYYY-MM-DD HH:mm:ss");
    },
    formatSite: function (row, column) {
      for (let i = 0; i < this.fsiteNoBelongOptions.length; i++) {
        if (row.fsiteNo === this.fsiteNoBelongOptions[i].value) {
          return this.fsiteNoBelongOptions[i].label;
        }
      }
      return "";
    },
    formatFstorageflag: function (row, column) {
      for (let i = 0; i < this.fstorageflagOptions.length; i++) {
        if (row.fstorageflag === this.fstorageflagOptions[i].value) {
          return this.fstorageflagOptions[i].label;
        }
      }
      return "";
    },
    formatFairitem: function (row, column) {
      for (let i = 0; i < this.sTsAiritemOptions.length; i++) {
        if (row.fairitem === this.sTsAiritemOptions[i].value) {
          return this.sTsAiritemOptions[i].label;
        }
      }
      return "";
    },
    addData() {
      this.dialogFormVisible1 = false;
      // this.dataForm.details.push(this.dataForm1);
      this.dataForm.details.push({
        fairitem: this.dataForm1.fairitem.value,
        fairitemname: this.dataForm1.fairitem.label,
        fwhere: this.dataForm1.fwhere,
        fwhere2: this.dataForm1.fwhere2,
        fvalue: this.dataForm1.fvalue,
        fvalue2: this.dataForm1.fvalue2,
      });
    },
    cancel() {
      this.dialogFormVisible = false;
      this.selectList = [];
      this.flineList = [];
      console.log("this.detailsTmp", this.detailsTmp);
      console.log("this.dataForm", this.dataForm);
      this.list.forEach((v) => {
        if (v.fsceneno === this.dataForm.fsceneno) {
          this.dataForm = this.listTmp;
          this.dataForm.details = this.detailsTmp;
          const index = this.list.indexOf(v);
          this.list.splice(index, 1, this.dataForm);
          return;
        }
      });
    },

    // 弹窗点击关闭前的回调
    handleClose() {
      this.dialogFormVisible = false;
      this.selectList = [];
      this.flineList = [];
      this.list.forEach((v) => {
        if (v.fsceneno === this.dataForm.fsceneno) {
          this.dataForm = this.listTmp;
          this.dataForm.details = this.detailsTmp;
          const index = this.list.indexOf(v);
          this.list.splice(index, 1, this.dataForm);
          return;
        }
      });
    },
    editData() {
      this.$refs["dataForm1"].validate((valid) => {
        if (valid) {
          this.dialogFormVisible1 = false;
          for (const v of this.dataForm.details) {
            if (v.fairitem === this.dataForm1.fairitem) {
              const index = this.dataForm.details.indexOf(v);
              this.dataForm.details.splice(index, 1, this.dataForm1);
              break;
            }
          }
        }
      });
    },
    getList() {
      this.listLoading = true;
      listsceneHead(this.listQuery)
        .then((response) => {
          this.list = response.data.data.list;
          this.total = response.data.data.total;
          this.listLoading = false;
        })
        .catch(() => {
          this.list = [];
          this.total = 0;
          this.listLoading = false;
        });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    resetForm() {
      this.dataForm = {
        fscenename: undefined,
        fsiteNo: undefined,
        fstorageflag: undefined,
        fexectime: undefined,
        fexecweek1: undefined,
        fexecweek2: undefined,
        fexecweek3: undefined,
        fexecweek4: undefined,
        fexecweek5: undefined,
        fexecweek6: undefined,
        fexecweek7: undefined,
        fscenetype: undefined,
        foperator: undefined,
        fupddate: undefined,
        id: undefined,
        details: [],
      };
    },
    resetForm1() {
      this.dataForm1 = {
        fairitem: undefined,
        fwhere: undefined,
        fvalue: undefined,
        fwhere2: undefined,
        fvalue2: undefined,
      };
    },
    handleCreate() {
      this.resetForm();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.dataForm.fscenetype = "2";
      this.dataForm.frange = 0;
      this.dataForm.fsiteNo = this.$store.state.user.fsiteNo;
       this.addrow(res=>{})

      // 子表1
      this.handleUpdate1();
      this.resetForm1();
      this.dataForm1.fno = 1;
    },
    createData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          createsceneHead(this.dataForm)
            .then((response) => {
              this.list.unshift(response.data.data);
              this.dialogFormVisible = false;
              this.$notify.success({
                title: "成功",
                message: "添加物料柜场景主表成功",
              });
              this.selectList = [];
              this.flineList = [];
            })
            .catch((response) => {
              this.$notify.error({
                title: "失败",
                message: response,
              });
            });
        }
      });
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row);
       this.addrow(res=>{})
      this.dataForm.fscenetype = "2";
      this.dataForm.frange = 0;
      this.detailsTmp = [];
      this.listTmp = row;
      row.details.forEach((v) => {
        this.detailsTmp.push(v);
        this.selectList.push(v.fairitem);
        this.flineList.push(v.fno);
      });
      this.dialogStatus = "upresetFormdate";
      this.dialogFormVisible = true;

      // 子表1
      this.handleUpdate1();
      this.resetForm1();
      if (this.dataForm.details.length > 0) {
        // 计算行号
        let len = this.dataForm.details.length - 1;
        this.dataForm1.fno = this.dataForm.details[len].fno + 1;
      } else {
        this.dataForm1.fno = 1;
      }
    },
    updateData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.dataForm.details.splice(this.dataForm.details.length-1,1);
          updatesceneHead(this.dataForm, this.$route.query.id)
            .then(() => {
              for (const v of this.list) {
                if (v.fsceneno === this.dataForm.fsceneno) {
                  const index = this.list.indexOf(v);
                  this.list.splice(index, 1, this.dataForm);
                  break;
                }
              }
              this.dialogFormVisible = false;
              this.$notify.success({
                title: "成功",
                message: "更新物料柜场景主表成功",
              });
              this.selectList = [];
              this.flineList = [];
            })
            .catch((response) => {
              this.$notify.error({
                title: "失败",
                message: response,
              });
            });
        }
      });
    },
    handleDelete(row) {
      this.$confirm("是否要删除物料柜场景主表", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deletesceneHead(row)
          .then((response) => {
            this.$notify.success({
              title: "成功",
              message: "删除物料柜场景主表成功",
            });
            const index = this.list.indexOf(row);
            this.list.splice(index, 1);
          })
          .catch((response) => {
            this.$notify.error({
              title: "失败",
              message: response,
            });
          });
      });
    },
    handleUpdate1() {
      this.$nextTick(() => {
        this.$refs["dataForm1"].clearValidate();
      });
    },

    // 子表一添加编辑
    handleEdit1(row) {
      this.dataForm1 = Object.assign({}, row);
      // 清除验证
      this.$nextTick(() => {
        this.$refs["dataForm1"].clearValidate();
      });
    },
    // 子表一编辑保存数据
    editData1() {
      this.$refs["dataForm1"].validate((valid) => {
        if (valid) {
          if (this.dataForm.details.length > 0) {
            let temp = [...this.dataForm.details];
            let isRepeat = false;
            // 子表编辑
            for (const v of this.dataForm.details) {
              if (v.fno === this.dataForm1.fno) {
                const index = this.dataForm.details.indexOf(v);
                // 判断物料是否重复
                temp.splice(index, 1);
                for (const vi of temp) {
                  if (vi.fairitem == this.dataForm1.fairitem) {
                    isRepeat = true;
                    this.$notify.error({
                      title: "失败",
                      message: "所选空气项目重复",
                    });
                    return;
                  }
                }

                if (!isRepeat) {
                  this.dataForm.details.splice(index, 1, this.dataForm1);
                  this.selectList.splice(index, 1, this.dataForm1.fairitem);
                  this.isAdd1 = false;
                  break;
                }
              }
            }
            // 子表添加
            if (this.isAdd1) {
              // 判断行号是否重复
              const flinetem = this.flineList.indexOf(this.dataForm1.fno);
              // 判断物料id是否重复
              const tem = this.selectList.indexOf(this.dataForm1.fairitem);
              if (flinetem < 0) {
                if (tem < 0) {
                  if (valid) {
                    this.dataForm.details.push(this.dataForm1);
                    this.selectList.push(this.dataForm1.fairitem);
                    this.flineList.push(this.dataForm1.fno);
                  }
                } else {
                  this.$notify.error({
                    title: "失败",
                    message: "所选物料重复",
                  });
                  return;
                }
              } else {
                this.$notify.error({
                  title: "失败",
                  message: "行号重复",
                });
                return;
              }
            }
          } else {
            // 子表第一次添加
            // 判断行号是否重复
            const flinetem = this.flineList.indexOf(this.dataForm1.fno);
            // 判断物料id是否重复
            const tem = this.selectList.indexOf(this.dataForm1.fairitem);
            if (flinetem < 0) {
              if (tem < 0) {
                if (valid) {
                  console.log("this.dataForm1", this.dataForm1);
                  this.dataForm.details.push(this.dataForm1);
                  this.selectList.push(this.dataForm1.fairitem);
                  this.flineList.push(this.dataForm1.fno);
                }
              } else {
                this.$notify.error({
                  title: "失败",
                  message: "所选物料重复",
                });
                return;
              }
            } else {
              this.$notify.error({
                title: "失败",
                message: "行号重复",
              });
              return;
            }
          }
          this.resetForm1();
          this.isAdd1 = true;
          // 清除验证
          this.$nextTick(() => {
            this.$refs["dataForm1"].clearValidate();
          });
          // 计算行号
          let len = this.dataForm.details.length - 1;
          this.dataForm1.fno = this.dataForm.details[len].fno + 1;
        }
      });
    },

    cancle1() {
      this.resetForm1();
      this.isAdd1 = true;

      // 清除验证
      this.$nextTick(() => {
        this.$refs["dataForm1"].clearValidate();
      });

      // 计算行号
      if (this.dataForm.details.length > 0) {
        // 计算行号
        let len = this.dataForm.details.length - 1;
        this.dataForm1.fno = this.dataForm.details[len].fno + 1;
      } else {
        this.dataForm1.fno = 1;
      }
    },

    handleDelete1(row) {
      const index = this.dataForm.details.indexOf(row);
      this.dataForm.details.splice(index, 1);
      this.selectList.splice(index, 1);
      this.flineList.splice(index, 1);
      this.resetForm1();
      // this.dataForm.details.pop(row)
    },

    indexMethod(index) {
      index = index + 1;
      return index;
    },
  },
};
</script>